package com.chaodroid.flyui.view.viewpager.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by CHEN on 2018/1/16.
 */

public abstract class FlyFragmentPagerAdapter extends FragmentPagerAdapter {

    private int mFragmentCount = 0;
    private List<Fragment> mFragments = null;
    private List<String> mTitles = null;

    public FlyFragmentPagerAdapter(FragmentManager fm, int fragmentCount, List<String> titles) {
        super(fm);
        mFragmentCount = fragmentCount;
        mFragments = new ArrayList<>(fragmentCount);
        mTitles = titles;
    }

    public FlyFragmentPagerAdapter(FragmentManager fm, int fragmentCount, String[] titles) {
        this(fm, fragmentCount, Arrays.asList(titles));
    }

    @Override
    public int getCount() {
        return mFragmentCount;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        if (mFragments != null) {
            //懒加载
            fragment = mFragments.get(position);
            if (fragment == null) {
                fragment = newFragmentInstance(position);
            }
        }
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles == null ? null : mTitles.get(position);
    }

    abstract public Fragment newFragmentInstance(int position);
}
